package com.yww.algorithm.sort;

import java.util.Arrays;

/**
 * @author yww
 * @description 冒泡排序
 * @since 2024/2/23 14:51
 */
public class BubbleSort {
    public static void sort(int[] arr) {
        doSort(arr);
    }

    /**
     * 迭代实现，优化版
     */
    private static void doSort(int[] arr) {
        int low = arr.length - 1;
        while (true) {
            if (low == 0) {
                break;
            }
            int x = 0;
            for (int i = 0; i < low; i++) {
                if (arr[i] > arr[i + 1]) {
                    int t = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = t;
                    x = i;
                }
            }
            low = x; // 优化，确定无序边界
        }
    }

    /**
     * 递归实现，优化版
     */
    private static void recur(int[] arr, int low) {
        if (low == 0) {
            return;
        }
        int x = low;
        for (int i = 0; i < low; i++) {
            if (arr[i] > arr[i + 1]) {
                int t = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = t;
                x = i;
            }
        }
        recur(arr, x);
    }

    public static void main(String[] args) {
        int[] a = {6, 5, 4, 3, 2, 1};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }

}
